<template>
  <div class="forum-page">
    <!-- 复用导航栏组件 -->
    <HeaderNav />
    
    <!-- 页面标题区 -->
    <section class="forum-header">
      <div class="container">
        <h1 class="page-title">{{ $t('forum.pageTitle') }}</h1>
        <p class="page-desc">{{ $t('forum.pageDesc') }}</p>
      </div>
    </section>
    
    <!-- 主内容区 -->
    <main class="forum-main">
      <div class="container">
        <!-- 论坛帖子展示区 -->
        <div class="forum-content">
          <!-- 帖子过滤工具栏 -->
          <div class="forum-toolbar">
            <div class="filter-options">
              <el-select v-model="activeFilter" placeholder="全部帖子" size="medium">
                <el-option label="全部帖子" value="all"></el-option>
                <el-option label="最新发布" value="latest"></el-option>
                <el-option label="热门讨论" value="hot"></el-option>
                <el-option label="精华帖子" value="精华"></el-option>
              </el-select>
            </div>
            <div class="search-box">
              <el-input 
                v-model="searchKeyword" 
                placeholder="搜索帖子..." 
                size="medium"
                prefix-icon="Search"
              ></el-input>
            </div>
            <div class="post-btn">
              <el-button type="primary" size="medium" @click="showCreatePostModal = true">
                <i class="iconfont icon-pencil"></i>
                {{ $t('forum.createPost') }}
              </el-button>
            </div>
          </div>
          
          <!-- 帖子列表 -->
          <div class="posts-list">
            <div 
              class="post-card" 
              v-for="(post, index) in posts" 
              :key="index"
              data-aos="fade-up"
              :data-aos-delay="index % 3 * 100"
            >
              <div class="post-header">
                <div class="user-info">
                  <img :src="post.authorAvatar" alt="用户头像" class="avatar">
                  <div class="user-details">
                    <div class="username">{{ post.authorName }}</div>
                    <div class="post-time">{{ formatDate(post.createTime) }}</div>
                  </div>
                </div>
                <div class="post-tags">
                  <el-tag v-for="(tag, i) in post.tags" :key="i" size="small">{{ tag }}</el-tag>
                </div>
              </div>
              
              <div class="post-content">
                <h3 class="post-title">{{ post.title }}</h3>
                <div class="post-excerpt">{{ post.excerpt }}</div>
                <div class="post-actions">
                  <button class="action-btn like-btn" @click="toggleLike(post.id)">
                    <i class="iconfont" :class="post.isLiked ? 'icon-like-fill' : 'icon-like'"></i>
                    <span class="count">{{ post.likeCount }}</span>
                  </button>
                  <button class="action-btn comment-btn" @click="toggleComments(post.id)">
                    <i class="iconfont icon-comment"></i>
                    <span class="count">{{ post.commentCount }}</span>
                  </button>
                  <button class="action-btn share-btn">
                    <i class="iconfont icon-share"></i>
                    <span>{{ $t('forum.share') }}</span>
                  </button>
                </div>
              </div>
              
              <!-- 评论区 -->
              <div class="post-comments" :class="{ 'expanded': post.showComments }">
                <div class="comments-list">
                  <div 
                    class="comment-item" 
                    v-for="(comment, cIndex) in post.comments" 
                    :key="cIndex"
                    v-if="cIndex < (post.showAllComments ? post.comments.length : 2)"
                  >
                    <img :src="comment.authorAvatar" alt="评论用户头像" class="comment-avatar">
                    <div class="comment-content">
                      <div class="comment-header">
                        <span class="comment-username">{{ comment.authorName }}</span>
                        <span class="comment-time">{{ formatDate(comment.createTime) }}</span>
                      </div>
                      <div class="comment-text">{{ comment.content }}</div>
                      <div class="comment-actions">
                        <button class="comment-action like" @click="likeComment(post.id, comment.id)">
                          <i class="iconfont" :class="comment.isLiked ? 'icon-like-fill' : 'icon-like'"></i>
                          <span>{{ comment.likeCount }}</span>
                        </button>
                        <button class="comment-action reply" @click="replyToComment(post.id, comment.id)">
                          <i class="iconfont icon-reply"></i>
                          <span>{{ $t('forum.reply') }}</span>
                        </button>
                      </div>
                    </div>
                  </div>
                  
                  <!-- 显示更多评论 -->
                  <div class="show-more-comments" v-if="post.comments.length > 2 && !post.showAllComments">
                    <button @click="post.showAllComments = true">
                      {{ $t('forum.showMoreComments', { count: post.comments.length - 2 }) }}
                    </button>
                  </div>
                  
                  <!-- 收起评论 -->
                  <div class="show-less-comments" v-if="post.comments.length > 2 && post.showAllComments">
                    <button @click="post.showAllComments = false">
                      {{ $t('forum.showLessComments') }}
                    </button>
                  </div>
                  
                  <!-- 添加评论 -->
                  <div class="add-comment" v-if="post.showComments">
                    <el-input
                      v-model="newCommentContent[post.id]"
                      placeholder="{{ $t('forum.writeComment') }}..."
                      type="textarea"
                      :rows="2"
                      class="comment-input"
                    ></el-input>
                    <div class="comment-submit">
                      <el-button 
                        type="primary" 
                        size="small"
                        @click="submitComment(post.id)"
                        :disabled="!newCommentContent[post.id]"
                      >
                        {{ $t('forum.submitComment') }}
                      </el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 30]"
              :total="totalPosts"
              layout="total, sizes, prev, pager, next, jumper"
              :prev-text="$t('pagination.prev')"
              :next-text="$t('pagination.next')"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </main>
    
    <!-- 页脚 -->
    <Footer />
    
    <!-- 创建帖子弹窗 -->
    <el-dialog 
      v-model="showCreatePostModal" 
      :title="$t('forum.createPost')"
      :width="dialogWidth"
      :close-on-click-modal="false"
    >
      <el-form :model="newPostForm" ref="postForm" :rules="postRules">
        <el-form-item label="$t('forum.postTitle')" prop="title">
          <el-input v-model="newPostForm.title" placeholder="$t('forum.enterTitle')"></el-input>
        </el-form-item>
        <el-form-item label="$t('forum.postContent')" prop="content">
          <el-input
            v-model="newPostForm.content"
            type="textarea"
            :rows="8"
            placeholder="$t('forum.enterContent')"
          ></el-input>
        </el-form-item>
        <el-form-item label="$t('forum.postTags')" prop="tags">
          <el-tag-input 
            v-model="newPostForm.tags" 
            :placeholder="$t('forum.enterTags')"
            :limit="3"
          ></el-tag-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreatePostModal = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="submitNewPost">{{ $t('common.submit') }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { formatDate } from '@/utils/date-utils'
import HeaderNav from '@/components/layout/HeaderNav.vue'
import Footer from '@/components/layout/Footer.vue'

// 国际化
const { t } = useI18n()

// 响应式状态
const currentPage = ref(1)
const pageSize = ref(10)
const totalPosts = ref(56)
const activeFilter = ref('all')
const searchKeyword = ref('')
const showCreatePostModal = ref(false)
const newCommentContent = ref({})

// 帖子数据
const posts = ref([
  {
    id: 1,
    title: "2025年金矿行业发展趋势分析与预测",
    excerpt: "随着全球经济复苏，金矿行业面临新的机遇与挑战。本文将从市场需求、技术创新、政策环境等多个维度，深入分析2025年金矿行业的发展趋势...",
    authorName: "矿业分析师",
    authorAvatar: "@/assets/images/bulding-bg.jpg",
    createTime: "2025-07-28T09:30:00",
    tags: ["行业分析", "趋势预测"],
    likeCount: 42,
    commentCount: 18,
    isLiked: false,
    showComments: false,
    showAllComments: false,
    comments: [
      {
        id: 101,
        authorName: "矿山投资人",
        authorAvatar: "@/assets/images/bulding-bg.jpg",
        createTime: "2025-07-28T10:15:00",
        content: "非常专业的分析，请问您如何看待新能源产业对金矿需求的影响？",
        likeCount: 8,
        isLiked: false
      },
      {
        id: 102,
        authorName: "采矿工程师",
        authorAvatar: "@/assets/images/bulding-bg.jpg",
        createTime: "2025-07-28T11:30:00",
        content: "技术创新部分分析得很到位，特别是自动化采矿设备的应用前景。我们矿场正在试点相关技术，效果显著。",
        likeCount: 12,
        isLiked: true
      },
      {
        id: 103,
        authorName: "市场观察员",
        authorAvatar: "@/assets/images/bulding-bg.jpg",
        createTime: "2025-07-28T14:20:00",
        content: "政策环境部分提到的环保要求趋严，确实是当前金矿企业面临的主要挑战之一。如何在环保与效益之间取得平衡，值得深入探讨。",
        likeCount: 5,
        isLiked: false
      }
    ]
  },
  {
    id: 2,
    title: "金矿开采新技术：环保与效率的平衡",
    excerpt: "传统金矿开采对环境造成的影响一直是行业痛点。本文介绍了几种新兴的环保开采技术，探讨如何在提高开采效率的同时，最大限度减少对环境的破坏...",
    authorName: "环保技术专家",
    authorAvatar: "@/assets/images/bulding-bg.jpg",
    createTime: "2025-07-26T15:45:00",
    tags: ["技术创新", "环境保护"],
    likeCount: 36,
    commentCount: 12,
    isLiked: true,
    showComments: false,
    showAllComments: false,
    comments: [
      {
        id: 201,
        authorName: "矿山管理者",
        authorAvatar: "@/assets/images/bulding-bg.jpg",
        createTime: "2025-07-26T16:20:00",
        content: "这些新技术的投入成本如何？中小型矿企是否能够负担得起？",
        likeCount: 6,
        isLiked: false
      },
      {
        id: 202,
        authorName: "环境学者",
        authorAvatar: "@/assets/images/bulding-bg.jpg",
        createTime: "2025-07-27T09:10:00",
        content: "生物浸出技术确实是未来的发展方向，但需要注意长期生态影响评估。",
        likeCount: 4,
        isLiked: false
      }
    ]
  },
  {
    id: 3,
    title: "金矿投资策略：2025年值得关注的区域市场",
    excerpt: "金矿投资一直是避险资金的重要选择。2025年，哪些区域市场值得投资者关注？本文将从政治稳定性、资源潜力、基础设施等方面进行评估...",
    authorName: "金融投资顾问",
    authorAvatar: "@/assets/images/bulding-bg.jpg",
    createTime: "2025-07-25T11:20:00",
    tags: ["投资分析", "市场动态"],
    likeCount: 58,
    commentCount: 24,
    isLiked: false,
    showComments: false,
    showAllComments: false,
    comments: [
      {
        id: 301,
        authorName: "个人投资者",
        authorAvatar: "@/assets/images/bulding-bg.jpg",
        createTime: "2025-07-25T13:40:00",
        content: "非洲地区的政治风险如何评估？这是我最关心的问题。",
        likeCount: 10,
        isLiked: false
      },
      {
        id: 302,
        authorName: "投资经理",
        authorAvatar: "@/assets/images/bulding-bg.jpg",
        createTime: "2025-07-25T15:15:00",
        content: "非常全面的分析，特别是对拉美地区的评估很有见地。",
        likeCount: 8,
        isLiked: true
      }
    ]
  }
])

// 新帖子表单
const newPostForm = reactive({
  title: '',
  content: '',
  tags: []
})

// 表单验证规则
const postRules = reactive({
  title: [
    { required: true, message: t('forum.titleRequired'), trigger: 'blur' },
    { min: 5, max: 100, message: t('forum.titleLength'), trigger: 'blur' }
  ],
  content: [
    { required: true, message: t('forum.contentRequired'), trigger: 'blur' },
    { min: 20, message: t('forum.contentMinLength'), trigger: 'blur' }
  ]
})

// 计算属性：弹窗宽度
const dialogWidth = computed(() => {
  return window.innerWidth < 768 ? '90%' : '600px'
})

// 方法：切换评论显示
const toggleComments = (postId) => {
  const post = posts.value.find(p => p.id === postId)
  if (post) {
    post.showComments = !post.showComments
    // 初始化评论输入框
    if (post.showComments && !newCommentContent.value[postId]) {
      newCommentContent.value[postId] = ''
    }
  }
}

// 方法：切换点赞
const toggleLike = (postId) => {
  const post = posts.value.find(p => p.id === postId)
  if (post) {
    post.isLiked = !post.isLiked
    post.likeCount += post.isLiked ? 1 : -1
  }
}

// 方法：点赞评论
const likeComment = (postId, commentId) => {
  const post = posts.value.find(p => p.id === postId)
  if (post) {
    const comment = post.comments.find(c => c.id === commentId)
    if (comment) {
      comment.isLiked = !comment.isLiked
      comment.likeCount += comment.isLiked ? 1 : -1
    }
  }
}

// 方法：回复评论
const replyToComment = (postId, commentId) => {
  // 此处简化处理，实际项目中可能需要打开回复框
  alert(t('forum.replyFunction'))
  
  // 自动展开评论区
  const post = posts.value.find(p => p.id === postId)
  if (post && !post.showComments) {
    post.showComments = true
    // 初始化评论输入框
    if (!newCommentContent.value[postId]) {
      newCommentContent.value[postId] = ''
    }
  }
}

// 方法：提交评论
const submitComment = (postId) => {
  const content = newCommentContent.value[postId]
  if (!content) return
  
  const post = posts.value.find(p => p.id === postId)
  if (post) {
    // 添加新评论
    const newComment = {
      id: Date.now(),
      authorName: "当前用户",
      authorAvatar: "@/assets/images/bulding-bg.jpg",
      createTime: new Date().toISOString(),
      content: content,
      likeCount: 0,
      isLiked: false
    }
    
    post.comments.unshift(newComment)
    post.commentCount += 1
    
    // 清空输入框
    newCommentContent.value[postId] = ''
    
    // 自动展开所有评论
    post.showAllComments = true
  }
}

// 方法：提交新帖子
const submitNewPost = () => {
  // 此处简化处理，实际项目中需要表单验证
  const newPost = {
    id: Date.now(),
    title: newPostForm.title,
    excerpt: newPostForm.content.substring(0, 150) + '...',
    authorName: "当前用户",
    authorAvatar: "@/assets/images/bulding-bg.jpg",
    createTime: new Date().toISOString(),
    tags: newPostForm.tags,
    likeCount: 0,
    commentCount: 0,
    isLiked: false,
    showComments: false,
    showAllComments: false,
    comments: []
  }
  
  // 添加到帖子列表顶部
  posts.value.unshift(newPost)
  totalPosts.value += 1
  
  // 关闭弹窗并重置表单
  showCreatePostModal.value = false
  newPostForm.title = ''
  newPostForm.content = ''
  newPostForm.tags = []
  
  // 提示成功
  ElMessage.success(t('forum.postCreatedSuccess'))
}

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val
  // 实际项目中这里应该重新获取数据
  console.log(`每页 ${val} 条`)
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // 实际项目中这里应该重新获取数据
  console.log(`当前页: ${val}`)
}

onMounted(() => {
  // 初始化评论输入对象
  posts.value.forEach(post => {
    newCommentContent.value[post.id] = ''
  })
  
  // 模拟数据加载
  console.log('论坛页面加载完成')
})
</script>

<style scoped lang="scss">
.forum-page {
  background: linear-gradient(90deg, 
    rgba(245, 247, 250, 1) 0%, 
    rgba(245, 247, 250, 0.8) 20%, 
    rgba(245, 247, 250, 0.5) 30%, 
    rgba(245, 247, 250, 0.5) 70%, 
    rgba(245, 247, 250, 0.8) 80%, 
    rgba(245, 247, 250, 1) 100%),
    url('@/assets/images/bulding-bg.jpg') repeat-y center;
  background-size: 100%, 1200px auto;
}

// 页面标题区
.forum-header {
  padding: 60px 0;
  text-align: center;
  background: linear-gradient(135deg, #0A2463 0%, #3E92CC 100%);
  color: white;
  margin-bottom: 40px;
  
  .page-title {
    font-size: 2.5rem;
    margin-bottom: 15px;
    font-weight: 700;
  }
  
  .page-desc {
    font-size: 1.1rem;
    max-width: 800px;
    margin: 0 auto;
    opacity: 0.9;
  }
}

// 主内容区
.forum-main {
  padding-bottom: 60px;
  
  .forum-content {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 15px rgba(0, 0, 0, 0.05);
    overflow: hidden;
  }
  
  // 工具栏
  .forum-toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 15px 20px;
    background-color: #f9fafb;
    border-bottom: 1px solid #f0f0f0;
    
    .filter-options {
      flex: 0 0 auto;
      margin-right: 15px;
      
      .el-select {
        width: 160px;
      }
    }
    
    .search-box {
      flex: 1 1 auto;
      margin: 0 15px;
      
      .el-input {
        max-width: 500px;
      }
    }
    
    .post-btn {
      flex: 0 0 auto;
      margin-left: 15px;
    }
    
    @media (max-width: 768px) {
      flex-wrap: wrap;
      
      .filter-options {
        width: 100%;
        margin-right: 0;
        margin-bottom: 10px;
        
        .el-select {
          width: 100%;
        }
      }
      
      .search-box {
        width: 100%;
        margin: 0 0 10px 0;
      }
      
      .post-btn {
        width: 100%;
        margin-left: 0;
      }
    }
  }
  
  // 帖子列表
  .posts-list {
    padding: 20px;
  }
  
  // 帖子卡片
  .post-card {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.03);
    padding: 20px;
    margin-bottom: 20px;
    transition: all 0.3s ease;
    
    &:hover {
      transform: translateY(-3px);
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
    }
    
    .post-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 15px;
      padding-bottom: 15px;
      border-bottom: 1px solid #f5f5f5;
      
      .user-info {
        display: flex;
        align-items: center;
        
        .avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          object-fit: cover;
          margin-right: 10px;
        }
        
        .user-details {
          .username {
            font-weight: 500;
            color: #333;
          }
          
          .post-time {
            font-size: 0.85rem;
            color: #999;
          }
        }
      }
      
      .post-tags {
        .el-tag {
          margin-left: 5px;
        }
      }
    }
    
    .post-content {
      .post-title {
        font-size: 1.3rem;
        margin-bottom: 10px;
        color: #0A2463;
        transition: color 0.3s ease;
        
        &:hover {
          color: #D8315B;
        }
      }
      
      .post-excerpt {
        color: #666;
        line-height: 1.6;
        margin-bottom: 15px;
        display: -webkit-box;
        -webkit-line-clamp: 3;
        -webkit-box-orient: vertical;
        overflow: hidden;
      }
      
      .post-actions {
        display: flex;
        gap: 15px;
        
        .action-btn {
          display: flex;
          align-items: center;
          gap: 5px;
          background: none;
          border: none;
          color: #666;
          font-size: 0.9rem;
          cursor: pointer;
          padding: 5px 10px;
          border-radius: 4px;
          transition: all 0.2s ease;
          
          &:hover {
            background-color: #f5f5f5;
            color: #D8315B;
          }
          
          .iconfont {
            font-size: 16px;
          }
          
          &.like-btn {
            .icon-like-fill {
              color: #D8315B;
            }
          }
        }
      }
    }
    
    // 评论区
    .post-comments {
      margin-top: 15px;
      padding-top: 15px;
      border-top: 1px dashed #f0f0f0;
      max-height: 0;
      overflow: hidden;
      transition: max-height 0.3s ease;
      
      &.expanded {
        max-height: 1000px;
      }
      
      .comments-list {
        .comment-item {
          display: flex;
          margin-bottom: 15px;
          
          .comment-avatar {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            object-fit: cover;
            margin-right: 10px;
            flex-shrink: 0;
          }
          
          .comment-content {
            flex: 1;
            background-color: #f9f9f9;
            padding: 12px 15px;
            border-radius: 18px;
            
            .comment-header {
              display: flex;
              justify-content: space-between;
              margin-bottom: 5px;
              
              .comment-username {
                font-weight: 500;
                font-size: 0.9rem;
              }
              
              .comment-time {
                font-size: 0.8rem;
                color: #999;
              }
            }
            
            .comment-text {
              font-size: 0.95rem;
              color: #333;
              margin-bottom: 8px;
            }
            
            .comment-actions {
              display: flex;
              gap: 15px;
              font-size: 0.85rem;
              
              .comment-action {
                background: none;
                border: none;
                color: #999;
                cursor: pointer;
                display: flex;
                align-items: center;
                gap: 3px;
                
                &:hover {
                  color: #D8315B;
                }
                
                .iconfont {
                  font-size: 14px;
                }
              }
            }
          }
        }
        
        .show-more-comments, .show-less-comments {
          text-align: center;
          margin-top: 10px;
          
          button {
            background: none;
            border: none;
            color: #D8315B;
            cursor: pointer;
            font-size: 0.9rem;
            
            &:hover {
              text-decoration: underline;
            }
          }
        }
        
        .add-comment {
          margin-top: 15px;
          
          .comment-input {
            margin-bottom: 10px;
          }
          
          .comment-submit {
            text-align: right;
          }
        }
      }
    }
  }
  
  // 分页
  .pagination {
    padding: 20px;
    text-align: center;
  }
}

// 响应式样式
@media (max-width: 768px) {
  .forum-header {
    padding: 40px 0;
    
    .page-title {
      font-size: 2rem;
    }
  }
  
  .post-card {
    padding: 15px;
    
    .post-header {
      flex-direction: column;
      
      .post-tags {
        margin-top: 10px;
        align-self: flex-start;
      }
    }
    
    .post-content {
      .post-title {
        font-size: 1.1rem;
      }
    }
  }
}
</style>